'use strict';

const { Role, Product, Op } = require('../model');

// 获取所有的角色（根据查找关键字过滤）
async function getAll(ctx, next) {
    let keyword = ctx.request.query.keyword;
    let obj = {};
    console.log('get')
    if (keyword) {
        obj = await Role.findAll({
            where: {
                [Op.or]: [
                    {
                        rolename: {
                            [Op.substring]: keyword
                        },
                    },
                    {
                        avatar: {
                            [Op.substring]: keyword
                        }
                    }
                ]


            }
        });
    } else {
        obj = await Role.findAll();
    }

    ctx.body = obj;
}
// 根据id获取指定的角色
async function getById(ctx, next) {
    let id = ctx.request.params.id;
    let obj = await Role.findByPk(id);
    ctx.body = obj;
}
// 新增
async function addItem(ctx, next) {
    let obj = ctx.request.body;
    await Role.create(obj);
    ctx.body = '增加成功'
}
// 修改
async function updateItem(ctx, next) {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;

    await Role.update(obj, {
        where: {
            id: id
        }
    });

    ctx.body = '修改成功';
}
//删除
async function delItem(ctx, next) {
    let id = ctx.request.params.id;
    await Role.destroy({
        where: {
            id: id
        }
    });

    ctx.body = '删除成功'
}

module.exports = {
    'get /roles': getAll,
    'get /roles/:id': getById,
    'post /roles': addItem,
    'put /roles/:id': updateItem,
    'del /roles/:id': delItem,
}